package com.yuyu.qingmangmall.ware.listener;

import com.rabbitmq.client.Channel;
import com.yuyu.common.to.mq.StockLockedTo;
import com.yuyu.qingmangmall.ware.service.WareOrderTaskDetailService;
import com.yuyu.qingmangmall.ware.service.WareOrderTaskService;
import com.yuyu.qingmangmall.ware.service.WareSkuService;
import com.yuyu.common.to.OrderTo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    /**
     *  1.库存自动解锁。
     *  下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚  之前锁定的库存就要自动解锁。
     *
     *  只要解锁库存的消息失败，一定要告诉服务解锁失败。
     * @param stockLockedTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void  handleStockLockedRelease(StockLockedTo stockLockedTo, Channel channel, Message message) throws IOException {
        System.out.println("要解锁的库存工作单的id为："+stockLockedTo.getTaskId());
        try {
            wareSkuService.unlockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

    /**
     * 取消订单时，尝试解锁库存
     * @param orderTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void  handleOrderCloseRelease(OrderTo orderTo, Channel channel, Message message) throws IOException {
        System.out.println("要解锁的库存订单的id为："+orderTo.getOrderSn());
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }


}
